package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    // 注入UserMapper
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpSession session;

    @Override
    public void register(User user) {
        // 取出邮箱和数据库中的做匹配
        String email = user.getEmail();
        User currentUser = userMapper.selectByEmailAndPassword(email, null);
        if (currentUser != null) {
            throw new RuntimeException("亲，该邮箱已注册");
        }

        // 设值默认的头像和背景
        user.setHeadImgUrl("/img/user/head.jpg");
        user.setCoverImgUrl("/img/user/bg.jpeg");
        // 设置默认积分

        // 注册成功将用户信息保存到数据库
        userMapper.insert(user);

    }

    @Override
    public User login(User user, String verify) {


        //如果有手机号,表示使用手机登录
        String phoneNumber = user.getPhoneNumber();
        if (phoneNumber != null) {
            //只匹配 session 里面的手机号和验证码, 缺一不可
            if (phoneNumber.equals(session.getAttribute("phoneNumber"))) {
                //如果phoneNumber有值,表示使用手机登录
                String loginVerify = session.getAttribute("verify").toString();

                System.out.println(loginVerify);
                System.out.println(session.getAttribute("phoneNumber"));


                if (!loginVerify.equals(verify)) {
                    //检验手机号和验证码是否是之前发送的
                    throw new RuntimeException("验证码不正确");
                }

                User currentUser = selectByPhoneNumber(phoneNumber);

                UserContext.setSession(currentUser);
                return currentUser;
            }
            //这里表示 session 里面的手机号和验证码不能同时匹配, 可能是获取密码后改了手机号,也可能没有获取验证码
            throw new RuntimeException("请先获取验证码");
        }


        // 判断当前用户名密码是否为空
        if (StringUtils.hasLength(user.getEmail()) && StringUtils.hasLength(user.getPassword())) {
            User currentUser = userMapper.selectByEmailAndPassword(user.getEmail(), user.getPassword());
            if (currentUser == null) {
                throw new RuntimeException("邮箱或密码错误");
            }
            // 将当前用户共享的session中
            UserContext.setSession(currentUser);
            return currentUser;
        }
        throw new RuntimeException("邮箱或密码不能为空");
    }

    @Override
    public PageInfo<User> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<User> list = userMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    @Override
    public void updata(User user) {
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User getUser(Long id) {
        System.out.println(id);
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addGrade(Long uId, Integer grade) {
        userMapper.addGrade(uId, grade);
    }

    @Override
    public void minusGrade(Long uId, Integer grade) {
        // 减积分前先判断是否够减
        Integer grades = getGradeById(uId);
        if (grades < grade){
            throw new RuntimeException("积分不足");
        }
        userMapper.minusGrade(uId, grade);
    }

    @Override
    public Integer getGradeById(Long userId) {
        return userMapper.selectGradeById(userId);
    }

    @Override
    public PageInfo<User> listGradeTop(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<User> list = userMapper.selectGradeTop(qo);
        return new PageInfo<>(list);
    }

    @Override
    public boolean validataBindPhoneNumber(String phoneNumber) {
        return userMapper.selectUserByPhoneNumber(phoneNumber) != null;
    }

    @Override
    public User selectByPhoneNumber(String phoneNumber) {

        return userMapper.selectUserByPhoneNumber(phoneNumber);
    }

    @Override
    public List<Long> selectForFollow(Long userId) {
        List<Long> ids = userMapper.selectForFollow(userId);
        return ids;
    }

    @Override
    public List<User> selectFollowUsers(List<Long> ids) {
        return userMapper.selectForFollows(ids);
    }

    @Override
    public List<Long> selectForFuns(Long id) {
        return userMapper.selectForFuns(id);
    }

    @Override
    public Object listInteresteds(Long userId) {
        return userMapper.listInteresteds(userId);
    }
}
